#!/usr/bin/env python3
"""
清理知识库相关数据的脚本
删除所有知识库文件、文件夹、分享链接、评论等数据
"""

import asyncio
import sys
import os
from motor.motor_asyncio import AsyncIOMotorClient

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app.core.config import settings
from app.core.database import get_minio
from minio.error import S3Error

async def clear_knowledge_data(clear_minio: bool = False):
    """清理所有知识库相关数据"""
    client = None
    minio_client = None
    
    try:
        # 连接到MongoDB
        client = AsyncIOMotorClient(settings.MONGODB_URL)
        db = client[settings.MONGODB_DATABASE]
        
        print("=" * 60)
        print("开始清理知识库相关数据...")
        print("=" * 60)
        
        # 1. 删除知识库评论
        comment_result = await db.knowledge_comments.delete_many({})
        print(f"✅ 删除知识库评论: {comment_result.deleted_count} 条")
        
        # 2. 删除知识库分享链接
        share_result = await db.knowledge_shares.delete_many({})
        print(f"✅ 删除知识库分享链接: {share_result.deleted_count} 条")
        
        # 3. 获取所有文件信息（用于删除MinIO文件）
        files_to_delete = []
        if clear_minio:
            async for file_doc in db.knowledge_files.find({}):
                if file_doc.get("file_path"):
                    files_to_delete.append(file_doc["file_path"])
        
        # 4. 删除知识库文件
        file_result = await db.knowledge_files.delete_many({})
        print(f"✅ 删除知识库文件: {file_result.deleted_count} 条")
        
        # 5. 删除知识库文件夹
        folder_result = await db.knowledge_folders.delete_many({})
        print(f"✅ 删除知识库文件夹: {folder_result.deleted_count} 条")
        
        # 6. 删除MinIO中的文件（可选）
        if clear_minio and files_to_delete:
            try:
                minio_client = get_minio()
                bucket_name = getattr(settings, "MINIO_BUCKET_NAME", "project-management")
                knowledge_prefix = "knowledge/files"
                
                deleted_count = 0
                for file_path in files_to_delete:
                    try:
                        minio_client.remove_object(bucket_name, file_path)
                        deleted_count += 1
                    except Exception as e:
                        print(f"⚠️  删除MinIO文件失败 {file_path}: {str(e)}")
                
                print(f"✅ 删除MinIO文件: {deleted_count}/{len(files_to_delete)} 个")
            except Exception as e:
                print(f"⚠️  删除MinIO文件时出错: {str(e)}")
        elif clear_minio:
            print("ℹ️  没有找到需要删除的MinIO文件")
        
        print("=" * 60)
        print("知识库数据清理完成！")
        print("=" * 60)
        
    except Exception as e:
        print(f"❌ 清理知识库数据失败: {str(e)}")
        import traceback
        traceback.print_exc()
    finally:
        if client:
            client.close()

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="清理知识库相关数据")
    parser.add_argument(
        "--clear-minio",
        action="store_true",
        help="同时删除MinIO中的文件（默认只删除数据库记录）"
    )
    
    args = parser.parse_args()
    
    asyncio.run(clear_knowledge_data(clear_minio=args.clear_minio))

